package com.chat.datea.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.StringRequest;
import com.chat.datea.R;
import com.chat.datea.base.Finnal_Base;
import com.chat.datea.bean.MusicList;
import com.chat.datea.bean.SongInfos;
import com.chat.datea.bean.greendao.Collect;
import com.chat.datea.bean.greendao.CollectDao;
import com.chat.datea.ui.MainActivity;
import com.chat.datea.ui.MusicActivity;
import com.chat.datea.utils.BaseTools.BaseTools;
import com.chat.datea.utils.daosingleton.DaoSingleton;
import com.chat.datea.utils.lrc.LyricDownloadManager;
import com.chat.datea.utils.mediautil.MediaUtil;
import com.chat.datea.utils.time.Time;
import com.chat.datea.utils.volley.VolleySingleton;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.dao.query.QueryBuilder;
import de.hdodenhof.circleimageview.CircleImageView;


/**
 * Created by YanBinXie on 15/10/28.
 */
public class MusicService extends Service implements MediaPlayer.OnCompletionListener,
        MediaPlayer.OnErrorListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnBufferingUpdateListener, IConstants, View.OnClickListener, SensorEventListener {

    private MediaPlayer player;
    private Timer timer;
    boolean prepared = false;
    private VolleySingleton singleton;
    private String name;
    private String singer;
    private String radioUrl;
    private ArrayList<MusicList> musicLists = new ArrayList<>();
    private int index;
    private Bitmap bitmap;
    private int mPlayMode;
    private Random mRandom;
    private CircleImageView music_img;
    private TextView music_name, music_time, music_timeAll, music_singer;
    private ImageView play, next, list;
    //定义浮动窗口布局
    private LinearLayout mFloatLayout;
    private WindowManager.LayoutParams wmParams;
    //创建浮动窗口设置布局参数的对象
    private WindowManager mWindowManager;
    private LinearLayout uprl;

    private SoundPool soundPool;
    private HashMap<Integer, Integer> soundID = new HashMap<>();
    /**
     * 通知栏按钮广播
     */
    public ButtonBroadcastReceiver bReceiver;
    /**
     * Notification管理
     */
    public NotificationManager mNotificationManager;

    /**
     * 是否在播放
     */
    public boolean isPlay = false;

    /**
     * 通知栏按钮点击事件对应的ACTION
     */
    public final static String ACTION_BUTTON = "com.notifications.intent.action.ButtonClick";
    public final static String INTENT_BUTTONID_TAG = "ButtonId";
    /**
     * 上一首 按钮点击 ID
     */
    public final static int BUTTON_PREV_ID = 1;
    /**
     * 播放/暂停 按钮点击 ID
     */
    public final static int BUTTON_PALY_ID = 2;
    /**
     * 下一首 按钮点击 ID
     */
    public final static int BUTTON_NEXT_ID = 3;
    public final static int BUTTON_CLEAN = 4;
    private Handler handler;
    private CollectDao collectDao;
    private SensorManager mSensorManager;
    private Vibrator mVibrator;
    private final int ROCKPOWER = 15;// 这是传感器系数
    /**
     * 歌词是否正在下载
     */
    private boolean mIsLyricDownloading;
    private LyricDownloadManager lyricDownloadManager;


    private static final String TAG = "MusicService";
    private String lyricFilePath;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MusicController();
    }


    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        singleton = VolleySingleton.getVolleySingleton(this);
        soundPool = new SoundPool(5, AudioManager.STREAM_SYSTEM, 5);
        soundID.put(1, soundPool.load(this, R.raw.duang, 1));
        Handler daoche = new Handler();
        daoche.postDelayed(runnable, 1000);
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        // 震动服务
        mVibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE); // 震动需要在androidmainfest里面注册哦亲
        // 加速度传感器
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                // 还有SENSOR_DELAY_UI、SENSOR_DELAY_FASTEST、SENSOR_DELAY_GAME等，
                // 根据不同应用，需要的反应速率不同，具体根据实际情况设定
                SensorManager.SENSOR_DELAY_NORMAL);
        handler = new Handler();
        lyricDownloadManager = new LyricDownloadManager();
        player = new MediaPlayer();
        player.setOnCompletionListener(this);
        player.setOnErrorListener(this);
        player.setOnPreparedListener(this);
        player.setOnBufferingUpdateListener(this);
        mPlayMode = MPM_LIST_LOOP_PLAY;
        mRandom = new Random();
        mRandom.setSeed(System.currentTimeMillis());
        collectDao = DaoSingleton.getInstance().getCollectDao();

        initButtonReceiver();

    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            soundPool.play(soundID.get(1), 1, 1, 0, 0, 1);
        }
    };


    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        Toast.makeText(this, "播放失败!我正在努力站起来!", Toast.LENGTH_SHORT).show();
        return false;
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        player.start();
        addTimer();
        prepared = true;
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {

    }

    /**
     * 悬浮窗口
     **/
    private void createFloatView() {
        wmParams = new WindowManager.LayoutParams();
        //获取的是WindowManagerImpl.CompatModeWrapper
        mWindowManager = (WindowManager) getApplication().getSystemService(getApplication().WINDOW_SERVICE);
        Log.i(TAG, "mWindowManager--->" + mWindowManager);
        //设置window type
        wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        //设置图片格式，效果为背景透明
        wmParams.format = PixelFormat.RGBA_8888;
        //设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        //调整悬浮窗显示的停靠位置为左侧置顶
        wmParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
        // 以屏幕左上角为原点，设置x、y初始值，相对于gravity
        wmParams.x = 0;
        wmParams.y = 0;

        //设置悬浮窗口长宽数据
        wmParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;


        LayoutInflater inflater = LayoutInflater.from(getApplication());
        //获取浮动窗口视图所在布局
        mFloatLayout = (LinearLayout) inflater.inflate(R.layout.activity_mini, null);

        music_img = (CircleImageView) mFloatLayout.findViewById(R.id.music_img);
        music_name = (TextView) mFloatLayout.findViewById(R.id.music_name);
        music_time = (TextView) mFloatLayout.findViewById(R.id.music_time);
        music_timeAll = (TextView) mFloatLayout.findViewById(R.id.music_timeAll);
        music_singer = (TextView) mFloatLayout.findViewById(R.id.music_singer);
        play = (ImageView) mFloatLayout.findViewById(R.id.play);
        next = (ImageView) mFloatLayout.findViewById(R.id.next);
        list = (ImageView) mFloatLayout.findViewById(R.id.list);

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (getIsPlay()) {
                    play.setImageResource(R.mipmap.bt_minibar_pause_normal);
                } else {
                    play.setImageResource(R.mipmap.bt_minibar_play_normal);
                }
                music_img.setImageBitmap(getRadioUrl());
                music_time.setText(Time.formatTime((long) getProgress()));
                music_timeAll.setText(Time.formatTime((long) getDuration()));
                music_name.setText(getName());
                music_singer.setText(getSinger());
                return false;
            }
        });


        //添加mFloatLayout
        mWindowManager.addView(mFloatLayout, wmParams);

        //浮动窗口按钮
        uprl = (LinearLayout) mFloatLayout.findViewById(R.id.uprl);

        mFloatLayout.measure(View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
                .makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        Log.i(TAG, "Width/2--->" + uprl.getMeasuredWidth() / 2);
        Log.i(TAG, "Height/2--->" + uprl.getMeasuredHeight() / 2);
        //设置监听浮动窗口的触摸移动
        uprl.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                //getRawX是触摸位置相对于屏幕的坐标，getX是相对于按钮的坐标
                wmParams.x = (int) event.getRawX() - uprl.getMeasuredWidth() / 2;
                Log.i(TAG, "RawX" + event.getRawX());
                Log.i(TAG, "X" + event.getX());
                //减25为状态栏的高度
                wmParams.y = (int) event.getRawY() - uprl.getMeasuredHeight() / 2 - 25;
                Log.i(TAG, "RawY" + event.getRawY());
                Log.i(TAG, "Y" + event.getY());
                //刷新
                mWindowManager.updateViewLayout(mFloatLayout, wmParams);
                return false;  //此处必须返回false，否则OnClickListener获取不到监听
            }
        });
        play.setOnClickListener(this);
        next.setOnClickListener(this);
        music_img.setOnClickListener(this);
        list.setOnClickListener(this);
    }


    private void loadLyricByHand(String musicName, String url) {
        // 取得歌曲同目录下的歌词文件绝对路径
        lyricFilePath = LyricDownloadManager.lrcPath + "/" + musicName + ".lrc";
        File lyricfile = new File(lyricFilePath);

        if (lyricfile.exists()) {
            // 本地有歌词，直接读取
            Log.i(TAG, "loadLyric()--->本地有歌词，直接读取");
            try {
                MusicActivity.getHelpter().loadLyric(getLyricFilePath());
            } catch (Exception e) {
            }
        } else {
            mIsLyricDownloading = true;
            // 尝试网络获取歌词
            Log.i(TAG, "loadLyric()--->本地无歌词，尝试从网络获取");
            new LyricDownloadAsyncTask().execute(musicName, url);

        }
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        int sensorType = event.sensor.getType();
        // values[0]:X轴，values[1]：Y轴，values[2]：Z轴
        float[] values = event.values;
        if (sensorType == Sensor.TYPE_ACCELEROMETER) {
            // 在 这个if里面写监听，写要摇一摇干么子，知道么？猪头~~~
            if ((Math.abs(values[0]) > ROCKPOWER || Math.abs(values[1]) > ROCKPOWER || Math.abs(values[2]) > ROCKPOWER)) {
                mVibrator.vibrate(300);// 设置震动。
                next();
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    class LyricDownloadAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            // 从网络获取歌词，然后保存到本地
            String lyricFilePath = lyricDownloadManager.fetchLyricContent(
                    params[0], params[1]);
            // 返回本地歌词路径
            mIsLyricDownloading = false;

            return lyricFilePath;
        }

        @Override
        protected void onPostExecute(String result) {
            Log.i(TAG, "网络获取歌词完毕，歌词保存路径:" + result);
            try {
                MusicActivity.getHelpter().loadLyric(getLyricFilePath());
            } catch (Exception e) {
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play:
                if (getIsPlay()) {
                    pause();
                } else if (getIsPlay() == false && getDuration() > getProgress()) {
                    continuePlay();
                }
                break;
            case R.id.next:
                next();
                break;
            case R.id.music_img:
                Intent intent = new Intent(this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;
            case R.id.list:
                playPrev();
                break;
        }

    }

    /**
     * 带按钮的通知栏点击广播接收
     */
    public void initButtonReceiver() {
        bReceiver = new ButtonBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_BUTTON);
        registerReceiver(bReceiver, intentFilter);
    }

    /**
     * 广播监听按钮点击时间
     */
    public class ButtonBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            if (action.equals(ACTION_BUTTON)) {
                //通过传递过来的ID判断按钮点击属性或者通过getResultCode()获得相应点击事件
                int buttonId = intent.getIntExtra(INTENT_BUTTONID_TAG, 0);
                switch (buttonId) {
                    case BUTTON_PREV_ID:
                        Log.d(TAG, "上一首");
                        playPrev();
                        Toast.makeText(getApplicationContext(), "上一首", Toast.LENGTH_SHORT).show();
                        break;
                    case BUTTON_PALY_ID:
                        String play_status = "";
                        isPlay = !isPlay;
                        if (isPlay) {
                            play_status = "开始播放";
                        } else {
                            play_status = "已暂停";
                        }
                        showButtonNotify();
                        if (getIsPlay()) {
                            pause();
                        } else if (getIsPlay() == false && getDuration() > getProgress()) {
                            continuePlay();
                        }
                        Log.d(TAG, play_status);
                        Toast.makeText(getApplicationContext(), play_status, Toast.LENGTH_SHORT).show();
                        break;
                    case BUTTON_NEXT_ID:
                        Log.d(TAG, "下一首");
                        next();
                        Toast.makeText(getApplicationContext(), "下一首", Toast.LENGTH_SHORT).show();
                        break;
                    case BUTTON_CLEAN:
                        try {
                            mNotificationManager.cancelAll();// 删除你发的所有通知
                        } catch (Exception e) {

                        }
                        break;
                }
            }
        }
    }

    /**
     * 带按钮的通知栏
     */
    public void showButtonNotify() {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
        RemoteViews mRemoteViews = new RemoteViews(getPackageName(), R.layout.view_custom_button);
        mRemoteViews.setImageViewBitmap(R.id.custom_song_icon, bitmap);
        //API3.0 以上的时候显示按钮，否则消失
        mRemoteViews.setTextViewText(R.id.tv_custom_song_singer, getSinger());
        mRemoteViews.setTextViewText(R.id.tv_custom_song_name, getName());
        //如果版本号低于（3。0），那么不显示按钮
        if (BaseTools.getSystemVersion() <= 9) {
            mRemoteViews.setViewVisibility(R.id.ll_custom_button, View.GONE);
        } else {
            mRemoteViews.setViewVisibility(R.id.ll_custom_button, View.VISIBLE);
            //
            if (isPlay) {
                mRemoteViews.setImageViewResource(R.id.btn_custom_play, R.mipmap.btn_pause);
            } else {
                mRemoteViews.setImageViewResource(R.id.btn_custom_play, R.mipmap.btn_play);
            }
        }

        //点击的事件处理
        Intent buttonIntent = new Intent(ACTION_BUTTON);
        /* 上一首按钮 */
        buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_PREV_ID);
        //这里加了广播，所及INTENT的必须用getBroadcast方法
        PendingIntent intent_prev = PendingIntent.getBroadcast(this, 1, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_prev, intent_prev);
        /* 播放/暂停  按钮 */
        buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_PALY_ID);
        PendingIntent intent_paly = PendingIntent.getBroadcast(this, 2, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_play, intent_paly);
        /* 下一首 按钮  */
        buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_NEXT_ID);
        PendingIntent intent_next = PendingIntent.getBroadcast(this, 3, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_next, intent_next);
        buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_CLEAN);
        PendingIntent intent_clean = PendingIntent.getBroadcast(this, 4, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mRemoteViews.setOnClickPendingIntent(R.id.clean, intent_clean);

        mBuilder.setContent(mRemoteViews)
                .setContentIntent(getDefalutIntent(Notification.FLAG_ONGOING_EVENT))
                .setWhen(System.currentTimeMillis())// 通知产生的时间，会在通知信息里显示
                .setPriority(Notification.PRIORITY_DEFAULT)// 设置该通知优先级
                .setOngoing(true)
                .setSmallIcon(R.mipmap.app_127px);
        Notification notify = mBuilder.build();
        notify.flags = Notification.FLAG_ONGOING_EVENT;
        mNotificationManager.notify(100, notify);
    }

    /**
     * @获取默认的pendingIntent,为了防止2.3及以下版本报错
     * @flags属性: 在顶部常驻:Notification.FLAG_ONGOING_EVENT
     * 点击去除： Notification.FLAG_AUTO_CANCEL
     */
    public PendingIntent getDefalutIntent(int flags) {
        PendingIntent pendingIntent = PendingIntent.getService(this, 1, new Intent(), flags);
        return pendingIntent;
    }


    class MusicController extends Binder implements MusicInterface {

        @Override
        public void play(ArrayList<MusicList> lists, int position) {
            musicLists = lists;
            index = position;
            MusicService.this.play(lists, position);
        }

        @Override
        public void pause() {
            MusicService.this.pause();
        }

        @Override
        public void playPrev() {
            MusicService.this.playPrev();
        }

        @Override
        public void continuePlay() {
            MusicService.this.continuePlay();
        }

        @Override
        public void seekTo(int progress) {
            MusicService.this.seekTo(progress);

        }

        @Override
        public boolean getIsPlay() {
            return MusicService.this.getIsPlay();
        }

        @Override
        public int getDuration() {
            return MusicService.this.getDuration();
        }

        @Override
        public int getProgress() {
            return MusicService.this.getProgress();
        }

        @Override
        public String getName() {
            return MusicService.this.getName();
        }

        @Override
        public String getSinger() {
            return MusicService.this.getSinger();
        }

        @Override
        public void next() {
            MusicService.this.next();
        }

        @Override
        public Bitmap getRadioUrl() {
            return MusicService.this.getRadioUrl();
        }

        @Override
        public String getUrl() {
            return MusicService.this.getUrl();
        }

        @Override
        public ArrayList<MusicList> getList() {
            return MusicService.this.getMusicLists();
        }

        @Override
        public int getPosition() {
            return MusicService.this.getIndex();
        }

        @Override
        public void stop() {
            MusicService.this.stop();
        }

        @Override
        public void setPlayMode(int mode) {
            MusicService.this.setPlayMode(mode);
        }

        @Override
        public int getmPlayMode() {
            return MusicService.this.getmPlayMode();
        }

        @Override
        public void background() {
            MusicService.this.background();
        }

        @Override
        public void go() {
            MusicService.this.go();
        }

        @Override
        public boolean isDownload() {
            return MusicService.this.isDownload();
        }

        @Override
        public String getLyricFilePath() {
            return MusicService.this.getLyricFilePath();
        }
    }

    public boolean isDownload() {
        return mIsLyricDownloading;
    }

    public String getLyricFilePath() {
        return lyricFilePath;
    }

    public void next() {
        if (musicLists != null && musicLists.size() > 0) {
            if (timer != null) {
                timer.cancel();
                timer = null;
            }
            switch (mPlayMode) {
                case MPM_LIST_LOOP_PLAY:
                    player.reset();
                    index++;
                    index = reviceIndex(index);
                    play(musicLists, index);
                    break;
                case MPM_ORDER_PLAY:
                    if (index != musicLists.size() - 1) {
                        player.reset();
                        index++;
                        index = reviceIndex(index);
                        play(musicLists, index);
                    } else {
                        index = 0;
                        play(musicLists, index);
                    }
                    break;
                case MPM_RANDOM_PLAY:
                    int indexs = getRandomIndex();
                    if (indexs != -1) {
                        index = indexs;
                    } else {
                        index = 0;
                    }
                    play(musicLists, index);
                    break;
                case MPM_SINGLE_LOOP_PLAY:
                    play(musicLists, index);
                    break;
            }

        } else {
            Toast.makeText(this, "请选择您喜欢的歌曲", Toast.LENGTH_SHORT).show();
        }

    }

    public void playPrev() {
        if (musicLists != null && musicLists.size() > 0) {
            if (timer != null) {
                timer.cancel();
                timer = null;
            }
            player.reset();
            index--;
            index = reviceIndex(index);
            play(musicLists, index);
        } else {
            Toast.makeText(this, "请选择您喜欢的歌曲", Toast.LENGTH_SHORT).show();
        }
    }


    private int reviceIndex(int index) {
        if (index < 0) {
            index = musicLists.size() - 1;
        }

        if (index >= musicLists.size()) {
            index = 0;
        }
        return index;
    }


    private int getRandomIndex() {
        int size = musicLists.size();
        if (size == 0) {
            return -1;
        }
        return Math.abs(mRandom.nextInt() % size);
    }


    //播放音乐
    public void play(final ArrayList<MusicList> lists, final int position) {


        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (lists != null && lists.size() > 0) {
            name = lists.get(position).getName();
            singer = lists.get(position).getSinger();
            //重置
            if (lists.get(position).getFrom().equals("网络")) {
                String url = Finnal_Base.apiUrl + Finnal_Base.method + "baidu.ting.song.getInfos"
                        + Finnal_Base.format + "&songid=" + lists.get(position).getSongId() + "&ts=1445582673704" +
                        "&e=Yv077YWCp4kyKb%2FthNHwKwMq52TU6BhTuyXiIob13Do%3D";
                StringRequest request = new StringRequest(url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Gson gson = new Gson();
                        SongInfos infos = gson.fromJson(response, SongInfos.class);
                        if (infos.getSongurl().getUrl() != null && infos.getSongurl().getUrl().size() > 0) {
                            String songUrl;
                            if (infos.getSongurl().getUrl().size() > 1) {
                                songUrl = infos.getSongurl().getUrl().get(1).getFile_link();
                            } else {
                                songUrl = infos.getSongurl().getUrl().get(0).getFile_link();
                            }
                            QueryBuilder qb = collectDao.queryBuilder();
                            qb.where(CollectDao.Properties.Name.eq(name));
                            qb.where(CollectDao.Properties.Want.eq("播放记录"));
                            ArrayList<Collect> collects = (ArrayList<Collect>) qb.list();
                            if (collects.size() > 0) {

                            } else {
                                Collect collect = new Collect();
                                collect.setName(name);
                                collect.setSinger(singer);
                                collect.setFrom("网络");
                                collect.setAlbumId((long) 0);
                                collect.setPosition(1);
                                collect.setId((long) 110);
                                collect.setSongId(lists.get(position).getSongId());
                                collect.setUrl(null);
                                collect.setWant("播放记录");
                                collectDao.insert(collect);
                            }


                            /**
                             * 下载歌词啊!有歌词会自动加载本地的歌词啊!
                             * */
                            loadLyricByHand(infos.getSonginfo().getTitle(), infos.getSonginfo().getLrclink());
                            radioUrl = infos.getSonginfo().getPic_premium();
                            ImageRequest imageRequest = new ImageRequest(radioUrl, new Response.Listener<Bitmap>() {
                                @Override
                                public void onResponse(Bitmap response) {
                                    bitmap = response;
                                    showButtonNotify();
                                }
                            }, 0, 0, Bitmap.Config.ARGB_8888, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {

                                }
                            });
                            singleton.addQueue(imageRequest, "MusicService");
                            if (player.isPlaying()) {
                                player.stop();
                            }
                            Log.e("MusicService", songUrl);
                            player.reset();
                            player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                            //加载多媒体文件
                            try {
                                player.setDataSource(songUrl);
                                player.prepareAsync();

                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
                singleton.addQueue(request, "MusicPlayer");
            } else if (lists.get(position).getFrom().equals("本地")) {
                String songUrl;
                songUrl = lists.get(position).getUrl();
                bitmap = MediaUtil.getArtwork(this, lists.get(position).getId(), lists.get(position).getAlbumId(), true, true);
                showButtonNotify();
                if (player.isPlaying()) {
                    player.stop();
                }
                player.reset();
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                //加载多媒体文件
                try {
                    player.setDataSource(songUrl);
                    player.prepareAsync();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                QueryBuilder qb = collectDao.queryBuilder();
                qb.where(CollectDao.Properties.Name.eq(name));
                qb.where(CollectDao.Properties.Want.eq("播放记录"));
                ArrayList<Collect> collects = (ArrayList<Collect>) qb.list();
                if (collects.size() > 0) {

                } else {
                    Collect collect = new Collect();
                    collect.setName(name);
                    collect.setSinger(singer);
                    collect.setFrom("网络");
                    collect.setAlbumId((long) 0);
                    collect.setPosition(1);
                    collect.setId((long) 110);
                    collect.setSongId(lists.get(position).getSongId());
                    collect.setUrl(null);
                    collect.setWant("播放记录");
                    collectDao.insert(collect);
                }


            }

        } else {
            Toast.makeText(this, "请选择您喜欢的歌曲", Toast.LENGTH_SHORT).show();
        }
    }

    public void setPlayMode(int mode) {
        switch (mode) {
            case MPM_LIST_LOOP_PLAY:
            case MPM_ORDER_PLAY:
            case MPM_RANDOM_PLAY:
            case MPM_SINGLE_LOOP_PLAY:
                mPlayMode = mode;
                break;
        }
    }

    public int getmPlayMode() {
        return mPlayMode;
    }

    public boolean getIsPlay() {
        return player.isPlaying();
    }

    //继续播放
    public void continuePlay() {
        player.start();
    }


    //暂停播放
    public void pause() {
        player.pause();
    }

    //重置播放
    public void stop() {
        player.reset();
    }

    public void seekTo(int progress) {
        player.seekTo(progress);
    }


    public ArrayList<MusicList> getMusicLists() {
        return musicLists;
    }

    public int getIndex() {
        return index;
    }

    public int getDuration() {
        int i = 0;
        if (prepared) {
            i = player.getDuration();
        }
        return i;
    }

    public int getProgress() {
        int i = 0;
        if (prepared) {
            i = player.getCurrentPosition();
        }
        return i;
    }

    public String getName() {
        return name;
    }

    public String getSinger() {
        return singer;
    }


    public void background() {
        createFloatView();
    }

    public void go() {
        if (mFloatLayout != null) {
            //移除悬浮窗口
            try {
                mWindowManager.removeView(mFloatLayout);
            } catch (Exception e) {

            }
        }
        try {
            mNotificationManager.cancelAll();// 删除你发的所有通知
        } catch (Exception e) {

        }
    }


    public void addTimer() {
        if (timer == null) {
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //获取歌曲总时长
                    int duration = player.getDuration();
                    //获取歌曲当前播放进度
                    int currentPosition = player.getCurrentPosition();
                    Message msg = MainActivity.handler.obtainMessage();
                    Message myMsg = handler.obtainMessage();
                    //把进度封装至消息对象中
                    Bundle bundle = new Bundle();
                    bundle.putInt("duration", duration);
                    bundle.putInt("currentPosition", currentPosition);
                    bundle.putInt("position", index);
                    msg.setData(bundle);
                    handler.sendMessage(myMsg);
                    MainActivity.handler.sendMessage(msg);
                }
                //开始计时任务后的5毫秒，第一次执行run方法，以后每500毫秒执行一次
            }, 5, 500);
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        mSensorManager.unregisterListener(this);// 退出界面后，把传感器释放。
        Log.e(TAG, "服务关闭");
        try {
            mNotificationManager.cancelAll();// 删除你发的所有通知
            mNotificationManager = null;
        } catch (Exception e) {

        }
        //释放占用的资源，此时player对象已经废掉了
        player.release();
        player = null;
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (bReceiver != null) {
            unregisterReceiver(bReceiver);
        }
        if (mFloatLayout != null) {
            //移除悬浮窗口
            try {
                mWindowManager.removeView(mFloatLayout);
            } catch (Exception e) {

            }
        }

    }

    public Bitmap getRadioUrl() {
        return bitmap;
    }


    public String getUrl() {
        return radioUrl;
    }


    @Override
    public void onCompletion(MediaPlayer mp) {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        next();

    }


}
